<?php

namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\web\IdentityInterface;
use yii\web\User;
class UserModel extends \yii\db\ActiveRecord implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['nickname', 'password', 'create_time'], 'required'],
            [['mobile', 'status', 'create_time'], 'integer'],
            [['nickname','name'], 'string', 'max' => 80],
            [['card_id','password'], 'string', 'max' => 255],
            [['mobile'], 'string', 'max' => 12],
            [['mobile'], 'unique'],
            [['mobile'],'match','pattern'=>'/^1[34578]{1}\d{9}$/','message'=>'手机号错误！'],
            //登录场景
            [['mobile'], 'unique', 'on' => ['add','edit'], 'message' => '{attribute}已被注册'],
            [['mobile', 'password'], 'required', 'on' => ['login'], 'message' => '{attribute}不能为空'],
            [['mobile'], 'required', 'on' => ['edit'], 'message' => '{attribute}不能为空'],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'nickname' => '昵称',
            'name' => '真是姓名',
            'password' => 'Password',
            'mobile' => '手机号码',
            'card_id' => '身份证号码',
            'status' => '状态，0正常 1禁用',
            'create_time' => 'Create Time',
        ];
    }

    /**
     * 验证前
     * @param bool $insert
     * @return bool
     */
    public function beforeValidate()
    {
        $time = time();
        if($this->isNewRecord){
            $this->create_time = $time;
            $this->status = 1;
            $this->password = Yii::$app->security->generatePasswordHash($this->password);
        }
        return parent::beforeValidate();
    }

    /**
     * 登录
     * @param $username
     * @return static
     */
    public function loginValidate()
    {
        $admin = self::findIdentityByMobile($this->mobile);
        if (empty($admin)) { return false;}//用户不存在
        if (Yii::$app->security->validatePassword($this->password, $admin->password)) {//存在，验证密码，验证通过返回identity实例
            return $admin;
        }
        return false;
    }

    /**
     * 根据用户名返回identity实例
     * @param $username
     * @return static
     */
    public static function findIdentityByMobile($mobile)
    {
        return static::findOne(['mobile' => $mobile]);
    }

    //identity
    public function getId()
    {
        return $this->id;
    }

    public function getAuthKey()
    {
        return empty($this->auth_key) ? '2018fengye2018' : $this->auth_key;
        //throw new NotSupportedException("auth key not support");
    }
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
        // return $this->password === $authKey;
    }
    public function validatePassword($passwd){
        return Yii::$app->getSecurity()->validatePassword($passwd,$this->password);
    }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException("access token not support");
    }

    //identity end

    public static function findByTelephone($telephone){
        return static::findOne(['telephone'=>$telephone,'status'=>1]);
    }
    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password = Yii::$app->security->generatePasswordHash($password);
    }
}
